package com.haiheng.module_main.fragment

import android.annotation.SuppressLint
import android.app.ScansManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.RadioGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.haiheng.common.dialog.StandardDialog
import com.haiheng.common.fragment.RouterFragment
import com.haiheng.library.log.LogUtils
import com.haiheng.library_base.adapter.BaseAdapter
import com.haiheng.library_base.dialog.LoadingDialog
import com.haiheng.library_base.model.ApplicationViewModel
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.msg.MsgCode
import com.haiheng.library_base.msg.MsgEvent
import com.haiheng.library_base.toast.ToastUtils
import com.haiheng.library_base.utils.FastClickUtil
import com.haiheng.module_main.R
import com.haiheng.module_main.adapter.BookListAdapter
import com.haiheng.module_main.databinding.FragmentBookWithdrawalBinding
import com.haiheng.module_main.mode.BookInfoViewModel
import com.haiheng.module_main.mode.BookWithdrawalViewModel
import kotlinx.coroutines.launch

/**
 *
 * @Des:图书下架
 * @Author: hwz
 * @Date:2023/6/17 0017
 * @Version: 1.0
 */
class BookWithdrawalFragment : RouterFragment() {
    private lateinit var binding: FragmentBookWithdrawalBinding
//    private val viewMode : DeploymentViewModel by viewModels()
    private val viewMode : BookInfoViewModel by viewModels()
    private lateinit var bookWithdrawalViewModel : BookWithdrawalViewModel
    private val bookListAdapter = BookListAdapter()
    private var mScansManager: ScansManager? = null
    //    private var broadcastReceiver: ScansReceiver? = null
    private lateinit var loadingDialog : LoadingDialog
    private var layerInfoSureDialog  : StandardDialog? = null


    private val observer = Observer<MsgEvent> { msgEvent ->
        onMessageChange(msgEvent)
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentBookWithdrawalBinding.inflate(inflater, container, false)
        return binding.root
    }
    override fun initView() {
        bookWithdrawalViewModel = BookWithdrawalViewModel(viewMode)
        loadingDialog = LoadingDialog(requireContext(), R.style.AvLoadingDialogStyle)
        binding.includeTile.rbTitleLeft.setText("单册下架")
        binding.includeTile.rbTitleRigh.setText("整层下架")
        binding.includeBottom.btnSubmit.setText("下架")
        binding.includeTile.ivBack.setOnClickListener {
            activity.navigateUp()
        }
        binding.includeTile.cbRignt.setOnClickListener {
            binding.includeTile.cbRignt.isChecked = true
            binding.includeIdentifyShelf.cbGetShelfNo.isChecked = false
//            mScansManager?.startScan()
        }
        binding.includeIdentifyShelf.cbGetShelfNo.setOnClickListener {
            binding.includeTile.cbRignt.isChecked = false
            binding.includeIdentifyShelf.cbGetShelfNo.isChecked = true
//            mScansManager?.startScan()
        }
        binding.includeTile.cbRignt.isChecked = true
        binding.includeIdentifyShelf.root.visibility = View.GONE

        binding?.rvBookList?.layoutManager = LinearLayoutManager(activity)
        binding?.rvBookList?.adapter = bookListAdapter
        bookListAdapter.setOnItemClickListener(object : BaseAdapter.OnItemClickListener{
            override fun onItemClick(holder: BaseAdapter.ViewBindHolder, position: Int) {
                var bookInfoBean = bookListAdapter.getItem(position)
                bookInfoBean.isSelect = !bookInfoBean.isSelect
                var isAllSelet = true
                for (b in bookListAdapter.getData()){
                    if (!b.isSelect){
                        isAllSelet = false
                        break
                    }
                }
                binding.includeBottom.cbAll.isChecked = isAllSelet
                bookListAdapter.notifyDataSetChanged()
            }
        })
        binding.includeBottom.cbAll.setOnClickListener {
            for (b in viewMode.bookListData.value!!){
                b.isSelect = binding.includeBottom.cbAll.isChecked
            }
            bookListAdapter.notifyDataSetChanged()
        }
        binding.includeBottom.btnSubmit.setOnClickListener {//下架
            loadingDialog.setMessage(getString(R.string.text_shlf_off_ing))
            loadingDialog.show()
//            if (binding.includeTile.rbTitleLeft.isChecked){
                bookWithdrawalViewModel.bookWithDrawalByList()
//            }else{
//                var layNo = binding.includeIdentifyShelf.etShelfNo.text.toString()
//                if (layNo.isNotBlank()){
//                    bookWithdrawalViewModel.bookWithDrawalByLayer(layNo)
//                }else{
//                    ToastUtils.showShort("层架号不能为空")
//                }
//            }


        }
        binding.includeBottom.btnClear.setOnClickListener {
            viewMode._bookListData.value = listOf()
            bookListAdapter.getData().clear()
            bookListAdapter.notifyDataSetChanged()
        }

        binding.includeIdentifyShelf.etShelfNo.setOnEditorActionListener {  v, keyCode, event ->
            LogUtils.e("ddddddd  keyCode${keyCode}")
            if(keyCode == EditorInfo.IME_ACTION_SEARCH) {
                binding.tvShelfNo.text = ""
                viewMode.getShelName(binding.includeIdentifyShelf.etShelfNo.text.toString())
                false
            }
            false
        }

        binding.includeTile.rgTitle.setOnCheckedChangeListener(object : RadioGroup.OnCheckedChangeListener{
            override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
                when(checkedId){
                    binding.includeTile.rbTitleLeft.id->{
                        binding.includeTile.cbRignt.visibility = View.VISIBLE
                        binding.includeTile.cbRignt.performClick()
                        binding.includeIdentifyShelf.root.visibility = View.GONE
                        binding.tvShelfNo.setText("")
                    }

                    binding.includeTile.rbTitleRigh.id->{
                        binding.includeIdentifyShelf.root.visibility = View.VISIBLE
                        binding.includeIdentifyShelf.etShelfNo.setText("")
                        binding.tvShelfNo.setText("")
                        viewMode._bookListData.postValue(listOf())
                        bookListAdapter.getData().clear()
                        bookListAdapter.notifyDataSetChanged()
                        binding.includeTile.cbRignt.visibility = View.GONE
                        binding.includeIdentifyShelf.cbGetShelfNo.performClick()
                    }
                }
            }
        })
    }

    override fun onResume() {
        super.onResume()
        observEven()
    }

    override fun onPause() {
        super.onPause()
        clearMsg()
        mScansManager?.stopScan()
    }

    override fun initViewModel(): BaseViewModel? {
        viewMode._bookListData.observe(viewLifecycleOwner){
            binding.tvBookNum.setText("数量：${it.size}")
            bookListAdapter.setNewData(it)

            var isAllSelet = true
            for (b in it){
                if (!b.isSelect){
                    isAllSelet = false
                    break
                }
            }
            binding.includeBottom.cbAll.isChecked = isAllSelet
        }
        viewMode.showMsg.observe(viewLifecycleOwner){
            ToastUtils.showShort(it)
            loadingDialog.hide()
        }
        viewMode.layerInfo.observe(viewLifecycleOwner){
            var content = "层架号：${it.outValue} \n名称：${it.name}"
            var listener  = object : StandardDialog.OnDialogClickListener{
                override fun onConfirm(dialog: StandardDialog) {
                    binding.tvShelfNo.setText(it.name)
                    viewMode.searchBookLisbByCurrentContainerId(it.outValue.toString())
                    dialog.dismiss()
                }

                override fun onCancel(dialog: StandardDialog) {
                    viewMode._bookListData.postValue(listOf())
                    dialog.dismiss()
                }
            }
            if (layerInfoSureDialog == null){
                layerInfoSureDialog = StandardDialog.newInstance().setTitle(getString(R.string.hint_layer_no))
            }
            layerInfoSureDialog?.setOnDialogListener(listener)
            layerInfoSureDialog?.setContent(content)
            if (!layerInfoSureDialog!!.isAdded){
                layerInfoSureDialog?.show(childFragmentManager)
            }
        }
        viewMode._bookInfoByBarcode.observe(viewLifecycleOwner){
            lifecycleScope.launch {
                viewMode.addBook(it)
            }
        }
        return viewMode
    }

    private fun onMessageChange(msgEvent: MsgEvent?) {
        when (msgEvent?.code){
            MsgCode.MSG_SCANS_BARCODE->{
                if (FastClickUtil.isFaskMsg(msgEvent.msg,200)) return //两次相同消息太快这不处理
                if (binding.includeTile.rbTitleRigh.isChecked &&
                    binding.includeIdentifyShelf.cbGetShelfNo.isChecked){//整架下架
                    if (layerInfoSureDialog?.isVisible == true) return
                    binding.includeIdentifyShelf.etShelfNo.setText(msgEvent.msg)
                    binding.tvShelfNo.text = ""
                    viewMode.getShelName(msgEvent.msg)

                }
                if (binding.includeTile.rbTitleLeft.isChecked
                    && binding.includeTile.cbRignt.isChecked){//单册下架
                    val barcodeExists = viewMode._bookListData.value?.any {
                        it.barCode.equals(msgEvent.msg)
                    }
                    if (barcodeExists == true) return
                    viewMode.searchBookInfoByBarCode(msgEvent.msg)
                }
            }
        }
    }

    private fun observEven() {
        if (ApplicationViewModel.get().even != null) {
            if (ApplicationViewModel.get().even.hasObservers()) {
                ApplicationViewModel.get().even.removeObserver(observer)
            }
            ApplicationViewModel.get().even.observe(this,observer)
        }
    }
    fun clearMsg(){
        if (ApplicationViewModel.get().even != null) {
            if (ApplicationViewModel.get().even.hasObservers()) {
                ApplicationViewModel.get().even.removeObserver(observer)
            }
        }
    }

    @SuppressLint("WrongConstant")
    override fun initLoad() {
        var manager   = activity.getSystemService("scans")
        if (manager != null){
            mScansManager = manager as ScansManager
            mScansManager?.persistMode =true
        }
//        if (mScansManager != null) {
//            inputmode = mScansManager!!.getInputMode()
//            addExtra = mScansManager!!.getExtras()
//        }


    }

}